﻿using System;
using System.Collections.Generic;
using System.Xml;
using Jayden.Dll.Core;

namespace Jayden.Dll.Web
{
	public class HtmlControlLoader
	{
		private Configuration m_Configuration;
		private Dictionary<string, Type> m_TypeByTagName = new Dictionary<string,Type>();

		public HtmlControlLoader(Configuration config)
		{
			m_Configuration = config;
			if (config != null)
			{
				string[] tagNames = config.GetValues("Control/@tag");
				if (tagNames != null && tagNames.Length > 0)
				{
					foreach (string tagName in tagNames)
					{
						string xpath = string.Format("Control[@tag=\"{0}\"]/@type", tagName);
						string typeName = m_Configuration.GetValue(xpath);
						if (typeName == null)
							throw new Exception(string.Format("No Type defined for tag=\"{0}\".", tagName));
						Type type = Type.GetType(typeName, true);
						RegisterType(tagName, type);
					}
				}
			}
		}

		public void RegisterType(string tagName, Type type)
		{
			m_TypeByTagName.Add(tagName, type);
		}
		public virtual bool Handle(string tagName, XmlNode node)
		{
			return m_TypeByTagName.ContainsKey(node.Name);
		}

		public Type GetType(string tagName)
		{
			Type type;
			if (m_TypeByTagName.TryGetValue(tagName, out type))
				return type;
			return null;
		}

		public Type this[string tagName] { get { return GetType(tagName); } }
	}
}
